﻿namespace Api.Controllers;

/// <summary>
/// 用户
/// </summary>
/// <param name="userBLL"></param>
/// <param name="roleBLL"></param>
/// <param name="configuration"></param>
/// <param name="idsUserService"></param>
/// <param name="operationLogBLL"></param>
[Route("api/[controller]/[action]")]
[ApiController]
[Authorize]
public class UserController(IUserBLL userBLL, IRoleBLL roleBLL, IConfiguration configuration, IIdsUserService idsUserService, IOperationLogBLL operationLogBLL) : BaseController(operationLogBLL)
{
    private readonly IUserBLL _userBLL = userBLL;
    private readonly IRoleBLL _roleBLL = roleBLL;
    private readonly IConfiguration _configuration = configuration;

    #region 用户列表分页
    /// <summary>
    /// 用户列表分页
    /// </summary>
    /// <returns></returns>
    [HttpPost]
    public async Task<ResultModel<List<UserVM>>> QueryPageListAsync([FromBody] UserQueryRM pageQuery)
    {
        RefAsync<int> total = 0;
        var userList = await _userBLL.QueryPageListAsync(pageQuery, total);
        var ret = new ResultModel<List<UserVM>>
        {
            data = userList,
            count = total,
        };
        return ret;
    }
    #endregion

    #region 设置用户角色
    /// <summary>
    /// 设置用户角色
    /// </summary>
    /// <param name="rm"></param>
    [HttpPost]
    public async Task<ResultModel> SetUserRoleByIdsAsync([FromBody] SetUserRoleByIdsRM rm)
    {
        var result = new ResultModel();
        var userList = await _userBLL.GetListAsync(x => rm.Ids.Contains(x.Id));
        if (userList == null || userList.Count == 0)
        {
            result.code = -1;
            result.msg = "未获取到用户！";
            return result;
        }
        var usernames = string.Join("、", userList.Select(x => x.Name));
        var role = await _roleBLL.GetListAsync(x => rm.RoleIds.Contains(x.Id));
        var rolename = string.Join("、", role.Select(x => x.Name));
        return await OperationExecuteCustomAsync(async () =>
        {
            var ret = await _userBLL.SetUserRoleByIdsAsync(rm);
            if (ret.code == 1)
            {
                result.code = 1;
                result.msg = "操作成功";
                result.data = true;
            }
            else
            {
                result.code = -1;
                result.msg = ret.msg;
            }
            result.data = ret.data;
            return result;
        }, new AddOperationLogInput { Content = $"设置用户[{usernames}]角色--{rolename}" });
    }
    #endregion

    #region 设置用户状态
    /// <summary>
    /// 设置用户状态
    /// </summary>
    /// <param name="rm"></param>
    [HttpPost]
    public async Task<ResultModel> SetUserEnableByIdsAsync([FromBody] SetEnableRM rm)
    {
        var result = new ResultModel();
        var userList = await _userBLL.GetListAsync(x => rm.Ids.Contains(x.Id));
        if (userList == null || userList.Count == 0)
        {
            result.code = -1;
            result.msg = "未获取到用户！";
            return result;
        }
        var usernames = string.Join("、", userList.Select(x => x.Name));
        return await OperationExecuteCustomAsync(async () =>
        {
            var result = new ResultModel();
            var ret = await _userBLL.SetUserEnableByIdsAsync(rm);
            if (ret.code == 1)
            {
                result.code = 1;
                result.msg = "操作成功";
                result.data = true;
            }
            else
            {
                result.code = -1;
                result.msg = ret.msg;
            }
            result.data = ret.data;
            return result;
        }, new AddOperationLogInput { Content = rm.Enable == 1 ? $"启用[用户]--{usernames}" : $"禁用[用户]--{usernames}" });
    }
    #endregion

    #region 同步用户
    /// <summary>
    /// 同步用户
    /// </summary>
    /// <returns></returns>
    [HttpGet]
    public ResultModel<string> ImportUserFromIDS()
    {
        return OperationExecuteReturnData(() =>
        {
            string importStudentTaskKey = "ts_import_user_from_ids";
            if (TaskManager.IsProcessing(importStudentTaskKey))
            {
                return importStudentTaskKey;
            }
            Task.Run(() =>
            {
                TaskManager.AddTask(importStudentTaskKey, new TaskInfo { Progress = 0 });
                SynUser(importStudentTaskKey);
                TaskManager.Remove(importStudentTaskKey);
            });
            return importStudentTaskKey;
        }, new AddOperationLogInput { Content = "同步用户" });
    }

    /// <summary>
    /// 同步用户
    /// </summary>
    private void SynUser(string? taskKey)
    {
        var pageIndex = 1;
        var pageSize = 200;
        var ids_appid = _configuration["IdServer:APPID"];
        var idsUserList = idsUserService.GetAppUserPageAsync(ids_appid, pageIndex, pageSize).Result;
        var count = idsUserList.Data.Total;
        int role = _configuration["IDSDefaultRoleId"] != null ? Convert.ToInt32(_configuration["IDSDefaultRoleId"]) : 0;
        while (idsUserList.Data.Rows.Length > 0)
        {
            try
            {
                var userList = _userBLL.GetList();
                var userAddList = new List<User>();
                var userUpdateList = new List<User>();
                foreach (var idsUser in idsUserList.Data.Rows)
                {
                    var userExist = userList.FirstOrDefault(x => x.Account == idsUser.Account);
                    var type = idsUser.TypeStr == UserTypeEnum.Other.ToDescription() ? (int)UserTypeEnum.Other : idsUser.TypeStr == UserTypeEnum.Teacher.ToDescription() ? (int)UserTypeEnum.Teacher : (int)UserTypeEnum.Student;
                    var gender = idsUser.GenderStr == GenderEnum.Unknown.ToDescription() ? (int)GenderEnum.Unknown : idsUser.GenderStr == GenderEnum.Male.ToDescription() ? (int)GenderEnum.Male : (int)GenderEnum.Female;
                    if (userExist == null)
                    {
                        var user = new User
                        {
                            Account = idsUser.Account,
                            RoleId = role,
                            Roles = [role],
                            Name = idsUser.Name,
                            Type = type,
                            Gender = gender,
                            Avatar = idsUser.Avatar,
                            OrgCode = idsUser.OrgCode,
                            OrgName = idsUser.OrgName,
                            Enable = 1,
                            CreateTime = DateTime.Now,
                            UserId = idsUser.UserId
                        };

                        if (idsUser.IsAdmin)
                        {
                            user.RoleId = 1;
                        }
                        userAddList.Add(user);
                    }
                    else
                    {
                        userExist.Name = idsUser.Name;
                        userExist.Type = type;
                        userExist.Gender = gender;
                        userExist.OrgCode = idsUser.OrgCode;
                        userExist.OrgName = idsUser.OrgName;
                        userExist.Avatar = idsUser.Avatar;
                        userExist.UserId = idsUser.UserId;
                        userUpdateList.Add(userExist);
                    }
                }
                if (userAddList.Any())
                {
                    _userBLL.Insert(userAddList);
                    userAddList.Clear();
                }
                if (userUpdateList.Any())
                {
                    _userBLL.Update(userUpdateList);
                    userUpdateList.Clear();
                }

                if (!string.IsNullOrWhiteSpace(taskKey))
                {
                    TaskManager.AddTask(taskKey, new TaskInfo { Progress = pageIndex * pageSize * 100 / count });
                }
                pageIndex += 1;
                idsUserList = idsUserService.GetAppUserPageAsync(ids_appid, pageIndex, pageSize).Result;
            }
            catch (Exception ex)
            {
                Log.WriteException(ex);
            }
        }
    }

    /// <summary>
    /// 同步用户调度
    /// </summary>
    [HttpGet]
    [AllowAnonymous]
    public ResultModel ImportUserFromJob()
    {
        var result = new ResultModel();
        try
        {
            SynUser(null);
            UserOperationLog(new AddOperationLogInput { Content = "同步用户" });
        }
        catch (Exception ex)
        {
            result.code = -1;
            result.msg = ex.Message;
            Log.WriteException(ex);
        }
        return result;
    }
    #endregion

    #region 根据角色id查询启用的用户列表
    /// <summary>
    /// 根据角色id查询启用的用户列表
    /// </summary>
    /// <param name="roleId">角色id</param>
    /// <returns></returns>
    [HttpGet]
    public async Task<ResultModel> GetEnableUserList(int roleId)
    {
        return await OperationExecuteCustomAsync(async () =>
        {
            var result = new ResultModel
            {
                data = await _userBLL.GetListAsync(x => SqlFunc.JsonArrayAny(x.Roles, roleId) && x.Enable == 1)
            };
            return result;
        });
    }
    #endregion

    #region 根据用户类型设置用户角色
    /// <summary>
    /// 根据用户类型设置用户角色
    /// </summary>
    /// <param name="rm"></param>
    [HttpPost]
    public async Task<ResultModel> SetUserRoleByUserTypeAsync([FromBody] SetUserRoleByUserTypeRM rm)
    {
        var result = new ResultModel();
        var role = await _roleBLL.GetAsync(x => rm.RoleIds.Contains(x.Id));
        var rolename = role != null ? role.Name : string.Empty;
        return await OperationExecuteCustomAsync(async () =>
        {
            #region 知识图谱设置
            //foreach(var roleId in rm.RoleIds)
            //{
            //	var userList = await _userBLL.GetListAsync(x => x.Type == rm.UserType);
            //	if (roleId < 3)
            //	{
            //		await _graphSetBLL.AddSetByUserIdsAsync(userList);
            //	}
            //	var deleteGraphSetUserList = new List<User>();
            //	foreach (var user in userList)
            //	{
            //		//如果从管理员改为其他角色
            //		if (user.RoleId < 3 && roleId > 2)
            //		{
            //			deleteGraphSetUserList.Add(user);
            //		}
            //	}
            //	if (deleteGraphSetUserList.Any())
            //	{
            //		await _graphSetBLL.DeleteSetByUserIdsAsync(userList);
            //	}
            //}
            #endregion
            var ret = await _userBLL.SetUserRoleByUserTypeAsync(rm);
            if (ret.code == 1)
            {
                result.code = 1;
                result.msg = "操作成功";
                result.data = true;
            }
            else
            {
                result.code = -1;
                result.msg = ret.msg;
            }
            result.data = ret.data;
            return result;
        }, new AddOperationLogInput { Content = $"类型授权[{((UserTypeEnum)(rm.UserType)).ToDescription()}]角色--{rolename}" });
    }
    #endregion

    #region 获取教师树
    /// <summary>
    /// 获取教师树
    /// </summary>
    /// <param name="rm">请求模型</param>
    /// <returns></returns>
    [HttpPost]
    public async Task<ResultModel> GetTeacherTree(TreeRM rm)
    {
        return await OperationExecuteCustomAsync(async () =>
        {
            var result = new ResultModel
            {
                data = await _userBLL.GetTeacherTree(rm)
            };
            return result;
        });
    }
    #endregion

    #region 获取学生树
    /// <summary>
    /// 获取学生树
    /// </summary>
    /// <param name="rm">请求模型</param>
    /// <returns></returns>
    [HttpPost]
    public async Task<ResultModel> GetStudentTree(TreeRM rm)
    {
        return await OperationExecuteCustomAsync(async () =>
        {
            var result = new ResultModel
            {
                data = await _userBLL.GetStudentTree(rm)
            };
            return result;
        });
    }
    #endregion

    #region 获取其他用户树
    /// <summary>
    /// 获取其他用户树
    /// </summary>
    /// <param name="rm">请求模型</param>
    /// <returns></returns>
    [HttpPost]
    public async Task<ResultModel> GetOtherListAsync(TreeRM rm)
    {
        return await OperationExecuteCustomAsync(async () =>
        {
            var result = new ResultModel
            {
                data = await _userBLL.GetOtherList(rm)
            };
            return result;
        });
    }
    #endregion

    #region 修改用户角色
    /// <summary>
    /// 修改用户角色
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    public async Task<ResultModel> UpdateUserRoleAsync([FromBody] UpdateUserRoleInput input)
    {
        return await OperationExecuteCustomAsync(async () =>
        {
            ResultModel result = new ResultModel();

            var ret = await _userBLL.UpdateUserRoleAsync(input);


            if (ret.code == 1)
            {
                result.code = 1;
                result.msg = "操作成功";
            }
            else
            {
                result.code = -1;
                result.msg = ret.msg;
            }
            result.data = ret.data;
            return result;
        });
    }
    #endregion

}
